// 观察者

import { popTarget, pushTarget } from "./dep";

let id = 0;
class Watcher {
  // vm, updateComponent, () => {},true
  constructor(vm, exprOrFn, cb, options) {
    this.vm = vm
    this.exprOrFn = exprOrFn
    this.cb = cb
    this.options = options
    this.id = id++
    // 默认执行一下exprOrFn ==>调了render 去vm上取值
    this.getter = exprOrFn
    this.get() //默认初始化 取值
    this.deps = []
    this.depsId = new Set()
  }
  get () {//用户更新时  重新调用get
    // defineProperty.get
    // 创建关联  每个属性收集自己的watcher
    // 一个属性对应多个watcher  一个watch对应多个属性
    pushTarget(this)  //Dep.target=watcher
    this.getter()
    popTarget()//防止用户在模板外使用
  }
  // watcher传dep
  addDep (dep) {
    let id = dep.id
    if (!this.depsId.has(id)) {
      this.depsId.add(id)
      this.deps.push(dep)
      // dep存watcher
      dep.addSub(this)
    }
  }
  // 更新
  update () {
    this.get()
  }
}
export default Watcher